package observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 此类用来对消息接收者实现，注册以及消息通知的操作。
 */
public class Saver {

    /**
     * 用来存放，已经注册的消息接收者。
     */
    private volatile List<Receiver> receivers;

    /**
     * 构造方法。
     */
    Saver() {
        receivers = new ArrayList<Receiver>();
    }

    /**
     * 通知符合条件的消息接收者，接收消息。
     * @param transmitter 消息传递者，它携带者要传递的消息。
     */
    void notifyReceiver(Transmitter transmitter) {
        for (Receiver receiver : receivers) {
            if (receiver.isEmpty()) {
                continue;
            }
            if (receiver.isContains(transmitter.getAction())) {
                boolean isEnd = receiver.receiver(transmitter);
                if (isEnd) {
                    return;
                }
            }
        }
    }

    /**
     * 注册消息接收者
     * @param receiver 要注册的消息接收者
     */
    void register(Receiver receiver) {
        this.receivers.add(receiver);
    }

    /**
     * 注销消息接收者
     * @param receiver 要注销的消息接收者
     */
    void unregister(Receiver receiver) {
        this.receivers.remove(receiver);
    }

    void close(){
        this.receivers.clear();
    }
}
